package msg

import (
	"context"
	"encoding/json"

	msgv1 "gitee.com/flycash/ws-gateway/api/proto/gen/gatewayapi/v1"

	"github.com/ecodeclub/mq-api"
)

type Producer interface {
	Produce(ctx context.Context, msg *msgv1.PushMessage) error
}

type producer struct {
	producer mq.Producer
	topic    string
}

func NewProducer(pro mq.Producer, topic string) Producer {
	return &producer{
		producer: pro,
		topic:    topic,
	}
}

func (p *producer) Produce(ctx context.Context, msgevt *msgv1.PushMessage) error {
	msgByte, err := json.Marshal(msgevt)
	if err != nil {
		return err
	}

	_, err = p.producer.Produce(ctx, &mq.Message{
		Value: msgByte,
		Topic: p.topic,
	})
	return err
}
